window.onload = function () {
	let newList = list //备份数据，方便修改
	let userList = [] //获取列表每一项
	rendering(newList) //初始渲染

	//搜索按钮
	search.addEventListener("click", () => update(document.querySelector('[name="name"]').value, document.querySelector('[name="gender"]').value, document.querySelector('[name="age"]').value))

	//重置按钮
	reset.addEventListener("click", () => {
		document.querySelector('[name="name"]').value = ""
		document.querySelector('[name="gender"]').value = ""
		document.querySelector('[name="age"]').value = ""
		update("", "", "") //更新
	})

	//删除按钮
	function deleteBtn() {
		document.querySelectorAll("#tbody tr td .btn").forEach(ele => {
			ele.addEventListener("click", function () {
				const id = this.dataset.index
				newList.splice(
					newList.findIndex(item => item.id == id),
					1
				)
				rendering(newList) //重新渲染
			})
		})
	}

	//搜索更新
	function update(name, gender, age) {
		userList.forEach(item => {
			item.style.display = "table-row"
			name != item.children[1].innerText && name && (item.style.display = "none")
			gender != item.children[2].innerText && gender && (item.style.display = "none")
			age != item.children[3].innerText && age && (item.style.display = "none")
		})
	}

	//排序数组
	function sort(arr) {
		let tempArr = arr
		for (let i = 0; i < tempArr.length; i++) {
			for (let j = 0; j < tempArr.length - i; j++) {
				if (j + 1 < tempArr.length) {
					if (tempArr[j].id > tempArr[j + 1].id) {
						const temp = tempArr[j + 1]
						tempArr[j + 1] = tempArr[j]
						tempArr[j] = temp
					}
				}
			}
		}
		return tempArr
	}

	//渲染页面
	function rendering(arr = []) {
		const newArr = sort(arr)
		tbody.innerHTML = ""
		newArr.forEach(item => {
			tbody.innerHTML += `
            <tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.gender}</td>
                <td>${item.age}</td>
                <td>
                    <button data-index="${item.id}" type="button" class="btn btn-danger">删除</button>
                </td>
            </tr>`
		})
		userList = document.querySelectorAll("#tbody tr") //重新获取列表
		deleteBtn() //删除按钮注册事件
	}
}
